#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
import base64

KEY = b'pmkt25y27gbjed5sdsazbkvo81t56344'

def pkcs7_pad(data: bytes) -> bytes:
    pad_len = 16 - (len(data) & 15)
    return data + bytes([pad_len]) * pad_len

def pkcs7_unpad(data: bytes) -> bytes:
    pad = data[-1]
    if pad > 16 or pad == 0 or any(b != pad for b in data[-pad:]):
        raise ValueError("无效的 PKCS7 填充")
    return data[:-pad]

def encrypt(plain: str) -> str:
    cipher = AES.new(KEY, AES.MODE_ECB)
    return base64.b64encode(cipher.encrypt(pkcs7_pad(plain.encode('utf-8')))).decode('utf-8')

def decrypt(cipher_b64: str) -> str:
    try:
        raw = base64.b64decode(cipher_b64.encode('utf-8'), validate=True)
    except Exception as e:
        raise ValueError("Base64 解码失败：" + str(e))
    if len(raw) % 16:
        raise ValueError("密文长度不是 16 字节整数倍")
    cipher = AES.new(KEY, AES.MODE_ECB)
    decrypted = cipher.decrypt(raw)
    try:
        return pkcs7_unpad(decrypted).decode('utf-8')
    except UnicodeDecodeError as e:
        raise ValueError("解密后不是合法 UTF-8：" + str(e))

def main():
    print("AES-256-ECB-PKCS7 循环加解密工具（Ctrl-C 退出）")
    try:
        while True:
            # ----------- 加密循环 -----------
            while True:
                print("====加密过程====")
                plain = input("请输入明文（留空跳过加密）：")
                if plain == "":
                    break
                try:
                    print("加密结果：", encrypt(plain))
                except Exception as e:
                    print("加密失败：", e)

            # ----------- 解密循环 -----------
            while True:
                print("====解密过程====")
                cipher = input("请输入密文（留空跳过解密）：")
                if cipher == "":
                    break
                try:
                    print("解密结果：", decrypt(cipher))
                except Exception as e:
                    print("解密失败：", e)
    except KeyboardInterrupt:
        print("\n已退出，再见！")

if __name__ == "__main__":
    main()
